﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Windows.UI.Core;

namespace SampleVariableGridView.Services
{
    public class ServiceRss
    {
        private string _apiKeyFlickr = "INSERT API KEY FLICKR";

        public void LoadListPhoto()
        {
            var request = (HttpWebRequest)HttpWebRequest.Create("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=" + _apiKeyFlickr + "&text=jakarta&sort=relevance&per_page=25");
            request.BeginGetResponse(new AsyncCallback(ReadCallback), request);
        }

        public async void ReadCallback(IAsyncResult asynchronousResult)
        {
            var request = (HttpWebRequest)asynchronousResult.AsyncState;
            var response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

            System.IO.Stream stream = response.GetResponseStream();
            var reader = new System.IO.StreamReader(stream);
            string stringResult = reader.ReadToEnd();

            var xml = XElement.Parse(stringResult);
            var data = from var in xml.Descendants("photo")
                       select new Models.Flickr()
                       {
                           Title = (var.Attribute("title").Value).ToUpper(),
                           Type = "Flickr",
                           ImageLarge = "http://farm" + var.Attribute("farm").Value + ".static.flickr.com/" + var.Attribute("server").Value + "/" + var.Attribute("id").Value + "_" + var.Attribute("secret").Value + ".jpg",
                           ImageUrl = "http://farm" + var.Attribute("farm").Value + ".static.flickr.com/" + var.Attribute("server").Value + "/" + var.Attribute("id").Value + "_" + var.Attribute("secret").Value + ".jpg"
                       };


            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                bool firstdata = false;
                Random rd = new Random();

                foreach (var p in data)
                {
                    var value = rd.Next(1, 5);
                    p.RowSpan = 2;
                    p.ColumnSpan = value;
                    App.EventAggregator.GetEvent<Events.EventFlickr>().Publish(p);
                    firstdata = true;
                }
            });
        }
    }
}
